//
//  BaseScene.m
//  HealthyLifestyle
//
//  Created by 找汽配 on 16/7/2.
//  Copyright © 2016年 祥运. All rights reserved.
//
//  登录是比较重要的动作，所以需要将登录层放到根部导航，以方便所有页面弹出登录层

#import "XYViewController.h"
#import "MBProgressHUD.h"
#import "WXApiManager.h"
#import "QQApiManager.h"
#import "IQKeyboardManager.h"
#import "HTTPRequestManager.h"
#import "XYPrefixHeader.pch"

// 权限检查
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import <AssetsLibrary/AssetsLibrary.h>

@interface XYViewController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate, HTTPRequestManagerDelegate, WXApiManagerDelegate, QQApiManagerDelegate>



@end

@implementation XYViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // 弹出消息框提示用户有订阅通知消息。主要用于用户在使用应用时，弹出提示框
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveRemoteNotification:) name:DidReceiveRemoteNotification object:nil];
    }
    return self;
}

- (void)dealloc {
    // 弹出消息框提示用户有订阅通知消息。主要用于用户在使用应用时，弹出提示框
    [[NSNotificationCenter defaultCenter] removeObserver:self name:DidReceiveRemoteNotification object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.automaticallyAdjustsScrollViewInsets = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)needLogin {
    return NO;
}

#pragma mark - Controller

- (BOOL)isPriceStringWhenInputting:(NSString *)string {
    if (string.length == 0 || [string isPrice]) {
        return YES;
    }
    else {
        return NO;
    }
}

- (NSInteger)seq {
    static NSInteger seq = 0;
    return ++seq;
}

#pragma mark - 相机 & 相册

- (void)selectImageWithImagePicker {
    // 调用相机的相关功能
    UIAlertController * controller = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction * cameraAction = [UIAlertAction actionWithTitle:@"打开相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self checkForCameraAuthorizationWithSuccess:^{
            [self openCamera];
        }];
    }];
    UIAlertAction * albumAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self checkForPhotoLibraryAuthorizationWithSuccess:^{
            [self openAlbum];
        }];
    }];
    [controller addAction:cancelAction];
    [controller addAction:cameraAction];
    [controller addAction:albumAction];
    if (self.navigationController) {
        [self.navigationController presentViewController:controller animated:YES completion:nil];
    }
    else {
        [self presentViewController:controller animated:YES completion:nil];
    }
}

- (void)openCamera {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController * picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.allowsEditing = YES;
        picker.delegate = self;
        if (self.navigationController) {
            [self.navigationController presentViewController:picker animated:YES completion:nil];
        }
        else {
            [self presentViewController:picker animated:YES completion:nil];
        }
    }
    else {
        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"无法打开相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertView show];
    }
}

- (void)openAlbum {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIImagePickerController * picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.allowsEditing = YES;
        picker.delegate = self;
        if (self.navigationController) {
            [self.navigationController presentViewController:picker animated:YES completion:nil];
        }
        else {
            [self presentViewController:picker animated:YES completion:nil];
        }
    }
    else {
        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"无法打开相册" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertView show];
    }
}

- (UIImage *)imageWithSourceType:(UIImagePickerControllerSourceType)sourceType info:(NSDictionary<NSString *,id> *)info {
    UIImage * originalImage = info[UIImagePickerControllerOriginalImage];
    CGRect rect = [info[UIImagePickerControllerCropRect] CGRectValue];
    if (sourceType == UIImagePickerControllerSourceTypeCamera) {
        rect = CGRectMake(rect.origin.y, originalImage.size.width - rect.origin.x - rect.size.width, rect.size.height, rect.size.width);
    }
    CGImageRef imageRef = CGImageCreateWithImageInRect([originalImage CGImage], rect);
    UIImage * result = [UIImage imageWithCGImage:imageRef scale:originalImage.scale orientation:originalImage.imageOrientation];
    CGImageRelease(imageRef);
    return result;
}

#pragma mark - 权限检查

// 检查相机权限
- (void)checkForCameraAuthorizationWithSuccess:(void(^)())success {
    // 扫描店铺二维码前，先检查是否允许访问摄像头
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    // 此应用程序没有被授权访问的照片数据。可能是家长控制权限
    // 用户已经明确否认了这一照片数据的应用程序访问
    if (status == AVAuthorizationStatusNotDetermined || status == AVAuthorizationStatusAuthorized) {
        if (success) {
            success();
        }
    }
    else {
        NSString * title = @"您未授权该应用访问您的相机，是否现在去授权？";
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"去授权" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            // 无权限，引导去开启
            NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:url]) {
                [[UIApplication sharedApplication] openURL:url];
            }
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

// 检查相册权限
- (void)checkForPhotoLibraryAuthorizationWithSuccess:(void(^)())success {
    // 打开相册前，先检查是否允许访问相册
    ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus];
    // 此应用程序没有被授权访问的照片数据。可能是家长控制权限
    // 用户已经明确否认了这一照片数据的应用程序访问
    if (status == ALAuthorizationStatusNotDetermined || status == ALAuthorizationStatusAuthorized) {
        if (success) {
            success();
        }
    }
    else {
        NSString * title = @"您未授权该应用访问您的照片，是否现在去授权？";
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"去授权" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            // 无权限，引导去开启
            NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:url]) {
                [[UIApplication sharedApplication] openURL:url];
            }
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

#pragma mark - Notification

// 已接收到推送
- (void)didReceiveRemoteNotification:(NSNotification *)notification {
    
}

#pragma mark - ProgressHUD

- (MBProgressHUD *)showProgressHUD {
    MBProgressHUD * hud = [[MBProgressHUD alloc] initWithView:self.view];
    hud.button.titleLabel.font = [UIFont systemFontOfSize:14];
    [hud.button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [hud.button setTitle:@"取消" forState:UIControlStateNormal];
    hud.removeFromSuperViewOnHide = YES;
    [self.view addSubview:hud];
    [hud showAnimated:YES];
    return hud;
}

- (void)hideProgressHUD:(MBProgressHUD *)hud {
    [hud hideAnimated:YES];
}

#pragma mark - Alert

- (void)presentAlertWithTitle:(NSString *)title message:(NSString *)message dismissAfterDelay:(NSTimeInterval)delay completion:(void(^)())completion {
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    if (completion) {
        [self presentViewController:alertController animated:YES completion:^{
            NSDictionary * dict = @{@"alert_controller":alertController,
                                    @"completion":completion};
            [self performSelector:@selector(dismissAlertControllerWithDict:) withObject:dict afterDelay:delay];
        }];
    }
    else {
        [self presentViewController:alertController animated:YES completion:^{
            [self performSelector:@selector(dismissAlertController:) withObject:alertController afterDelay:delay];
        }];
    }
}

- (void)dismissAlertController:(UIAlertController *)alertController {
    [alertController dismissViewControllerAnimated:YES completion:nil];
}

- (void)dismissAlertView:(UIAlertView *)alertView {
    [alertView dismissWithClickedButtonIndex:0 animated:YES];
}

- (void)dismissAlertControllerWithDict:(NSDictionary *)dict {
    UIAlertController * controller = dict[@"alert_controller"];
    [controller dismissViewControllerAnimated:YES completion:^{
        void(^completion)() = dict[@"completion"];
        completion();
    }];
}

- (void)dismissAlertViewWithDict:(NSDictionary *)dict {
    UIAlertView * view = dict[@"alert_view"];
    [view dismissWithClickedButtonIndex:view.cancelButtonIndex animated:YES];
    void(^completion)() = dict[@"completion"];
    completion();
}

#pragma mark - Login

- (void)presentLogin {

}

#pragma mark - HTTPRequestManagerDelegate

- (MBProgressHUD *)httpRequestManagerShowProgressHUD {
    return [self showProgressHUD];
}

- (void)httpRequestManagerHideProgressHUD:(MBProgressHUD *)hud {
    [self hideProgressHUD:hud];
}

- (void)httpRequestManagerDidRequestWarnWithContent:(NSString *)content {
    [self presentAlertWithTitle:@"提示" message:content dismissAfterDelay:PRESENT_DELAY completion:nil];
}

- (void)httpRequestManagerDidRequestErrorWithErrorCode:(ErrorCode)errorCode content:(NSString *)content {
    if (content.length == 0) {
        content = [XYEnum descriptionWithErrorCode:errorCode];
    }
    if (content.length == 0) {
        content = WarnHTTPRequestError;
    }
    [self presentAlertWithTitle:@"提示" message:content dismissAfterDelay:PRESENT_DELAY completion:nil];
}

- (void)httpRequestManagerDidRequestFailureWithError:(NSError *)error {
    [self presentAlertWithTitle:@"提示" message:WarnHTTPRequestError dismissAfterDelay:PRESENT_DELAY completion:nil];
}

- (void)httpRequestManagerDidInvalid {
    [self presentLogin];
}

- (void)httpRequestManagerDidCancel {

}

- (void)httpRequestManagerDidTimeOut {
    
}

- (void)httpRequestManagerDidOffline {
    [self presentAlertWithTitle:@"提示" message:WarnHTTPRequestError dismissAfterDelay:PRESENT_DELAY completion:nil];
}

#pragma mark - WXApiManagerDelegate

- (void)managerDidRecvGetMessageReq:(GetMessageFromWXReq *)req {
    
}

- (void)managerDidRecvShowMessageReq:(ShowMessageFromWXReq *)req {
    
}

- (void)managerDidRecvLaunchFromWXReq:(LaunchFromWXReq *)req {
    
}

- (void)managerDidRecvMessageResponse:(SendMessageToWXResp *)response {
    
}

- (void)managerDidRecvAddCardResponse:(AddCardToWXCardPackageResp *)response {
    
}

- (void)managerDidRecvAuthResponse:(SendAuthResp *)response {
    
}

#pragma mark - QQApiManagerDelegate

- (void)qqManagerDidGetMessageFromQQReq:(GetMessageFromQQReq *)request {
    
}

- (void)qqManagerDidSendMessageToQQReq:(SendMessageToQQReq *)request {
    
}

- (void)qqManagerDidShowMessageFromQQReq:(ShowMessageFromQQReq *)request {
    
}

- (void)qqManagerDidGetMessageFromQQResp:(QQBaseResp *)response {
    
}

- (void)qqManagerDidSendMessageToQQResp:(SendMessageToQQResp *)response {
    
}

- (void)qqManagerDidShowMessageFromQQResp:(QQBaseResp *)response {
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
